package com.aqie.security.demo.controller;

import com.aqie.security.demo.response.ResponseModel;
import com.aqie.security.demo.dto.User;
import com.aqie.security.demo.dto.condition.UserQueryCondition;
import com.aqie.security.demo.service.UserServiceImpl;
import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * @Function:
 * @Author: aqie
 * @Date: 2019/4/3 11:44
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    // 或者注入 Authentication
    @GetMapping("/me")
    public Object getCurrentUser(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @GetMapping(value = "/name",produces = "application/json;charset=UTF-8")
    public ResponseModel<User> getUserByName(@RequestParam("username") String name){
        User user = userService.findUserByUsername(name);
        return ResponseModel.success(user);
    }

    @PostMapping
    @ApiOperation(value = "创建用户")
    public User create(@Validated @RequestBody User user, BindingResult errors){
        if (errors.hasErrors()){
            errors.getAllErrors().forEach(error -> System.out.println(((FieldError) error).getField() + " "
                    + error.getDefaultMessage()));
        }
        return userService.createOrUpdate(user);
    }

    @PutMapping("/{id:\\d+}")
    public User update(@Validated @RequestBody User user, @PathVariable("id") int id, BindingResult errors){
        user.setId(id);
        Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
        user.setUpdateTime(new Timestamp(date.getTime()));
        return userService.createOrUpdate(user);
    }

    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User select(@PathVariable int id){
        return userService.select(id);
    }

    @GetMapping
    @JsonView(User.UserSimpleView.class)
    public List<User> userList(@Validated @RequestBody  UserQueryCondition condition){
        return userService.selectAll(condition).getContent();
    }

    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable("id") int id){
        userService.delete(id);
    }
}
